import { refreshToken } from '@/apis/login'
import { storage } from '@/store/sessionStorage'
import axios from 'axios'
import { ElMessage } from 'element-plus'
/**
 * 校验输入的密码，至少8位，包含数字+字母
 * @param password
 */
export const checkPassword = (password: string) => {
    let result = false
    if (password == '' || password == null || password.length < 8) {
        result = false
        return false
    }
    const reg = new RegExp(/^(?![^a-zA-Z]+$)(?!\D+$)/)
    if (reg.test(password)) {
        result = true
    }
    return result
}

export const checkPassword_2 = (val: string) => {
    /**
     * 正则表达式说明:
     * ^                 开始符，表示字符串的开始
     * (?=.*[a-zA-Z])    断言，确保至少有一个字母
     * (?=.*\d)          断言，确保至少有一个数字
     * (?=.*[._~!@#$^&*]) 断言，确保至少包含一个指定的特殊符号
     * [a-zA-Z\d._~!@#$^&*]{8,20} 匹配字母、数字和指定特殊符号，长度为8到20位
     * $                 结束符，表示字符串的结束
     */
    const passwordPattern = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[._~!@%#$^&*])[a-zA-Z\d._~!@#$%^&*]{8,20}$/

    return passwordPattern.test(val)
}

/**
 * 验证手机号码
 * @param mobile
 * @returns
 */
export const regMobile = (mobile: string) => {
    return /^1[3456789]\d{9}$/.test(mobile)
}
/**
 * 验证输入的银行卡号
 * @param card
 * @returns
 */
export const regBankAccount = (card: string) => {
    return /^([1-9]{1})(\d{15}|\d{16}|\d{18})$/.test(card)
}

/**
 *
 * @param data      数据源
 * @param key       每一项的ID key
 * @param parentKey 每一项的父级ID key
 * @returns []
 *
 * handleTree(list,'id','parentId')
 */
export function handleTree(data: any[], key: string, parentKey: string) {
    //创建一个空数组
    const result: any[] = []

    //创建一个map数组
    const map = new Map()
    map.clear()

    data.map((item: any) => {
        //以每一项的id值作为键
        map.set(item[key], item)
    })

    data.forEach((item: any) => {
        //从map中取出item对应的父值
        const parent = map.get(item[parentKey])

        //判断其父是否存在
        if (parent) {
            //存在则把 item 添加到 parent.children 中
            if (parent.children) {
                parent.children.push(item)
            } else {
                parent.children = []
                parent.children.push(item)
            }
        } else {
            //不存在 则添加到 result 中
            result.push(item)
        }
    })

    return result
}

//通过秒转换时间
export const timeFilterToSeconds = (seconds: number) => {
    let ss: number | string = parseInt(seconds.toString()) // 秒
    let mm: number | string = 0 // 分
    let hh: number | string = 0 // 小时
    if (ss > 60) {
        mm = Number(parseInt((ss / 60).toString()))
        ss = parseInt((ss % 60).toString())
    }
    if (mm > 60) {
        hh = parseInt((mm / 60).toString())
        mm = parseInt((mm % 60).toString())
    }
    let result = ('00' + parseInt(ss.toString())).slice(-2)
    if (mm > 0) {
        result = ('00' + parseInt(mm.toString())).slice(-2) + '分:' + result + '秒'
    } else {
        result = '00分:' + result + '秒'
    }
    if (hh > 0) {
        result = ('00' + parseInt(hh.toString())).slice(-2) + '时:' + result
    }
    return result
}

//设置倒计时
export class CountDown {
    //定时器
    timer: number | undefined | NodeJS.Timer

    //当前时间
    currentTime = 0

    //截至时间
    endTime = 0

    //当前时间距离截至时间
    intervalTime = 0

    //用户登录时间
    userLoginTime = 0

    second = 0

    //second 秒
    constructor(second: number) {
        console.log('second', second)
        this.second = second
        this.currentTime = new Date().getTime()
        //获取登录时间
        this.userLoginTime = Number(storage.get('loginTime'))

        /**
         * 从登录时间开始计算 倒计时 second分钟
         *
         * 1、创建登录时间对象
         * const loginDate = new Date(this.userLoginTime)
         * 2、通过loginDate得到分钟
         * const loginMinute = loginDate.getMinutes()
         * 3、
         * const endMinute = loginMinute + second
         * 4、
         * const e = loginDate.setMinutes(endMinute)
         * 5、再new Date()
         * const endDate = new Date(e)
         * 6、调用
         * this.endTime = endDate.getTime()
         */

        const loginDate = new Date(this.userLoginTime)
        //Date.setMinutes(min, sec, millisec) min必需。表示分钟的整数。
        // this.endTime = new Date(loginDate.setMinutes(loginDate.getMinutes() + Math.round(this.minute))).getTime()
        this.endTime = new Date(loginDate.setSeconds(loginDate.getSeconds() + Math.round(this.second))).getTime()

        console.log(
            second,
            '登录时间',
            this.userLoginTime,
            '当前时间',
            this.currentTime,
            '相差',
            timeFilterToSeconds((this.currentTime - this.userLoginTime) / 1000),
            '截至时间',
            this.endTime
        )
        clearInterval(storage.get('countDownTimer'))
    }
    start(callback = () => {}) {
        this.stop()
        let s = 0
        this.timer = setInterval(() => {
            this.currentTime = new Date().getTime()
            this.intervalTime = this.endTime - this.currentTime // 两个时间戳相隔的毫秒数
            s = parseInt((this.intervalTime / 1000).toString())
            // console.log(this.intervalTime)
            if (s > 0) {
                // console.log('time', timeFilterToSeconds(s))
            } else {
                refreshToken().then(e => {
                    //this.setToken(e.data.result.accessToken)
                    storage.set('loginTime', new Date().getTime().toString())
                    storage.set('token', e.data.result.accessToken)
                    storage.set('refreshToken', e.data.result.refreshToken)
                    storage.set('expire', (e.data.result.expire - 5).toString())
                    new CountDown(this.second).start()
                })
                this.stop(callback)
            }
        }, 1000)

        storage.set('countDownTimer', this.timer.toString())
    }
    stop(callback = () => {}) {
        if (this.timer) {
            clearInterval(this.timer as number)
            callback()
        }
    }
}

//创建下载
export const CreateXMLHttpRequest = (url: string, fileName: string) => {
    const xhr = new XMLHttpRequest()
    xhr.open('get', url, true)
    xhr.responseType = 'blob'
    xhr.setRequestHeader('cxl-token', storage.get('token'))
    xhr.onload = function () {
        if (xhr.status === 200) {
            // console.log('xhr.response', xhr)
            const blob = new Blob([this.response], { type: 'application/vnd.ms-excel;charset=utf-8' })
            const a = document.createElement('a')
            const u = window.URL.createObjectURL(blob)
            a.href = u
            a.download = fileName + '.xlsx'
            a.click()
            window.URL.revokeObjectURL(url)
        }
    }
    xhr.send()
}

//axios创建下载
export const CreateAxiosDownload = (url: string, fileName: string) => {
    axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: {
            'cxl-token': storage.get('token')
        }
    }).then(res => {
        console.log('res', res.request, res.data.text())
        res.data.text().then((e: any) => {
            //判断返回是否是字符串
            if (!isJSON(e)) {
                const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
                const a = document.createElement('a')
                const u = window.URL.createObjectURL(blob)
                a.href = u
                a.download = fileName + '.xlsx'
                a.click()
                window.URL.revokeObjectURL(url)
            } else {
                const data = JSON.parse(e)
                ElMessage.error(data.message)
            }
        })
    })
}

export function isJSON(str: string) {
    try {
        JSON.parse(str)
    } catch (e) {
        // 转换出错，抛出异常
        return false
    }
    return true
}

//file文件转base64
export const fileToBase64Async = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = (e: any) => {
            resolve(e.target.result as string)
        }
    })
}
//计算两个日期之间的天数
export function getDaysBetweenDates(date1: string, date2: string) {
    // 将日期字符串转换为时间戳
    const timestamp1 = new Date(date1).getTime()
    const timestamp2 = new Date(date2).getTime()

    // 计算两个时间戳之间的天数
    const days = Math.ceil(Math.abs(timestamp2 - timestamp1) / (1000 * 3600 * 24))

    return days
}

//为富文本中的图片添加display:block;属性
export const addDisplayBlockToImages = (html: string) => {
    html = html.replace(/<img[^>]*src=/g, '<img style="display:block;width:100%; "src=')
    console.log('html', html)

    return html
}

//date格式化
export const formatTime = (date: Date) => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = (n: number) => {
    const s = n.toString()
    return s[1] ? s : '0' + s
}

// 生成四位随机字母
export function generateRandomLetters() {
    let result = ''
    const characters = 'abcdefghijklmnopqrstuvwxyz'
    for (let i = 0; i < 4; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length))
    }
    return result
}
